<?php
/**
 * appRain v 0.1.x
 *
 * LICENSE
 *
 * This source file is subject to the MIT license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://www.opensource.org/licenses/mit-license.php
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@apprain.com so we can send you a copy immediately.
 *
 * @copyright  Copyright (c) 2010 appRain, Team. (http://www.apprain.com)
 * @license    http://www.opensource.org/licenses/mit-license.php MIT license
 *
 * HELP
 *
 * Official Website
 * http://www.apprain.com/
 *
 * Download Link
 * http://www.apprain.com/download
 *
 * Documents Link
 * http ://www.apprain.com/docs
 */

class Component_Photocliping_Helpers_Data extends appRain_Base_Objects
{
	public $adminId = 0;
	public $statuslist = Array('Pending'=>'Pending',
							   'Priceing'=>'Quotation',
							   //'Approved'=>'Approved',
							   'Started'=>'Started',
							   //'AwaitingPayment'=>'AwaitingPayment',
							   'Complete'=>'Complete');
	public $statusTitle = Array('Pending'=>'Waiting for Quote','Priceing'=>'Awaiting for Approval','Approved'=>'Started','Started'=>'Started','AwaitingPayment'=>'AwaitingPayment','Complete'=>'Completed');
	public $paidableStatus = array("approved","started","complete"); //,"complete"

	const COLOR_TIME12   = '#ebec9b';
	const COLOR_TIME14   = '#d68075';
	const COLOR_NOTCOMPLETE = '#d41f26';
	const COLOR_TIMEXTRA = '#a265ad';
	const COLOR_TIMEON   = '#69e569';

	public function __construct()
	{
		$this->adminId = App::getUserStatusId();
	}

	public function sendEmail($action="",$options=array())
	{
		switch($action)
		{
			case "NewJobSubmitted" :
				$Member = App::Model("Member")->findByid($options['Job']['client_id']);
				App::setUserStatusId(0);
				App::Helper('EmailTemplate')->setParameters(Array(
																'Name'=>$Member['name'],
																'Email'=>$Member['name']['email'],
                                                                'JobName'=>$options['Job']['title']
                                                        ))
                                        ->prepare("NewJobSubmitted",true);
										break;
			case "QutationSubmitted" :
				$Job = App::Model("Job")->findByid($options['jobid']);
				$Member = App::Model("Member")->findByid($Job['client_id']);
				App::setUserStatusId(0);
				App::Helper('EmailTemplate')->setParameters(Array(
																'Name'=>$Member['name'],
																'Email'=>$Member['name']['email'],
                                                                'JobName'=>$Job['title']
                                                        ))
                                        ->setTo(array($Member['email'],"{$Member['name']['name']}"))
                                        ->prepare("QutationSubmitted",true);
										break;
			case "JobApproved" :
				$Job = App::Model("Job")->findByid($options['jobid']);
				$Member = App::Model("Member")->findByid($Job['client_id']);
				App::setUserStatusId(0);
				App::Helper('EmailTemplate')->setParameters(Array(
																'Name'=>$Member['name'],
																'Email'=>$Member['name']['email'],
                                                                'JobName'=>$Job['title']
                                                        ))
                                        ->prepare("JobApproved",true);
										break;
			case "JobCompleted" :
				$Job = App::Model("Job")->findByid($options['jobid']);
				$Member = App::Model("Member")->findByid($Job['client_id']);
				App::setUserStatusId(0);
				App::Helper('EmailTemplate')->setParameters(Array(
																'Name'=>$Member['name'],
																'Email'=>$Member['name']['email'],
                                                                'JobName'=>$Job['title']
                                                        ))
                                        ->setTo(array($Member['email'],"{$Member['name']['name']}"))
                                        ->prepare("JobCompleted",true);
										break;
		}
	}

	public function createJobFirstInstanceGetId()
	{
		$data = App::Model('Job')->findByToken($this->getToken());

		if(!empty($data))
		{
			return $data['id'];
		}
		else
		{
			App::Model('Member')->setId($this->getClientId())->setModified(time())->Save();

			return   App::Model('Job')
						->setClient_id($this->getClientId())
						->setService_id($this->getServiceId())
						->setTitle($this->getTitle())
						->setToken($this->getToken())
						->setDescription($this->getDescription())
						->setDelivery_time($this->getDeliveryTime())
						->setDelivery_type($this->getDeliveryType())
						->setStatus('Pending')
						->setCreated(time())
						->Save()
						->getId();
		}
	}

	public function finalizeJobById($token)
	{
		$JobData = App::Model('Job')->findByToken($token);
		$this->sendEmail("NewJobSubmitted",array('Job'=>$JobData));
        
        if(strtolower($JobData['downloadtype']) !=  'ftp')
        {
		    $itemData = App::Model('File')->find("job_id={$JobData['id']}",null,"count(*) as cnt");

		    $JobData['num_images'] = $itemData['cnt'];
        }
		App::Model('Job')->Save(Array("Job"=>$JobData));

		return $JobData['id'];
	}

	public function allFilesById($id)
	{
		return App::Model('File')->paging("job_id={$id}");
	}

	public function statusbox($status)
	{
		if(!$this->adminId)
		{ 
            $mp = $this->statuslist;
            if(!(strtolower($status) == 'started') && $status != 'Complete')
            {
                 unset($mp['Complete']);
            }
			return App::Helper("Html")->selectTag("data[Job][status]",$mp,$status);
		}
		else
		{
			return $status;
		}

	}

	public function rateBox($File)
	{
		if(!$this->adminId)
		{
			return App::Helper("Html")->inputTag("data[Item][rate][{$File['id']}]",$File['rate'],array("style"=>"border:1px solid #DDD;padding:5px;width:40px;font-size:12px"));
		}
		else
		{
			return $File['rate'];
		}
	}

	public function downloadBox($link="")
	{
		if($this->adminId)
		{
			if($link!="") return App::Helper('Html')->linkTag(App::Config()->baseUrl("/pcjobs/download/" . base64_encode($link)),"Downlaod");
			else return "Not Added!";
		}
		else
		{
			$html =  App::Helper("Html")->inputTag("data[Job][download_link]",$link) . " <b>Example:</b> /data/abc.zip<br />";

			if($link!="") return  $html . "<br />" . App::Helper('Html')->linkTag(App::Config()->baseUrl("/pcjobs/download/" . base64_encode($link)),"Downlaod");

			return $html;
		}
	}

	public function displayStatus($status="")
	{
		return $this->statusTitle[$status];
	}

	public function displayStatusLink($Job)
	{
		$html = "";
		if($Job['status'] == 'Priceing' && $this->adminId)
		{
			$html .= " | " . App::Helper('Html')->linkTag(App::Config()->baseUrl("/pcjobs/changestatus/Started/{$Job['id']}"),"Approve");
		}
//pre($Job['paymentstatus']);
		if($Job['paymentstatus'] == 'NotPaid'  && !$this->adminId && in_array(strtolower($Job['status']),$this->paidableStatus))
		{
			$html .= " " .  App::Helper('Html')->linkTag(App::Config()->baseUrl("/pcjobs/payment/" . $Job['client_id'] . "/adjustpayment/{$Job['id']}"),App::Helper('Html')->imgTag(App::Config()->baseUrl("/images/admin/pay.jpg"))) . " ";
		}

		return $html;
	}

	public function addPayment()
	{

		$PdoObj = App::Model('Payment')->setClient_id($this->getClientId())
					 ->setProcessor($this->getProcessor())
					 ->setOrder_date($this->getOrder_date())
					 ->setOrder_number(time())
					 ->setTotal($this->getAmount())
					 ->setStatus('Success')
					 ->Save();

		$accountData = App::Model('Account')->findByClient_id($this->getClientId());

		$id = isset($accountData['id'])?$accountData['id']:null;
		$balance = isset($accountData['balance'])?($accountData['balance']+$this->getAmount()):$this->getAmount();
		$created = isset($accountData['created'])?$accountData['created']:time();
		$updated = time();
		$modified = time();

		// Update Balance
		App::Model('Account')
			->setId($id)
			->setClient_id($this->getClientId())
			->setBalance($balance)
			->setCreated($created)
			->setUpdated($updated)
			->setModified($modified)
			->Save();

		App::Module('Log')->Write("Payment $ {$this->getAmount()} Added to  Client Id :{$this->getClientId()}");
		$this->adjustPayment($this->getClientId());
	}

	public function deductPayment($jobid="")
	{
		$accountData = App::Model('Account')->findByClient_id($this->getClientId());
		if(empty($accountData) || $accountData['balance'] < $this->getAmount())
		{
			App::Module('Notification')->Push("Sorry! Not enough Balance");
			return false;
		}


		$PdoObj = App::Model('Expense')->setClient_id($this->getClientId())
					 ->setProcessor($this->getProcessor())
					 ->setPay_date(time())
					 ->setJob_id($jobid)
					 ->setTotal($this->getAmount())
					 ->Save();

		$accountData = App::Model('Account')->findByClient_id($this->getClientId());

		$id = isset($accountData['id'])?$accountData['id']:null;
		$balance = isset($accountData['balance'])?($accountData['balance']-$this->getAmount()):0;
		$created = isset($accountData['created'])?$accountData['created']:time();
		$updated = time();
		$modified = time();

		// Update Balance
		App::Model('Account')
			->setId($id)
			->setClient_id($this->getClientId())
			->setBalance($balance)
			->setCreated($created)
			->setUpdated($updated)
			->setModified($modified)
			->Save();

		App::Module('Log')->Write("Payment $ {$this->getAmount()} Deducted to  Client Id :{$this->getClientId()}");
		App::Module('Notification')->Push( $this->getAmount() . " Deducted from account");
		return true;
	}

	public function adjustPayment($client_id=null, $jobid=null)
	{
		if(isset($jobid)) $data = App::Model('Job')->findAll("id={$jobid} AND paymentstatus='NotPaid'");
		else $data = App::Model('Job')->findAll("client_id={$client_id} AND status='Approved' AND paymentstatus='NotPaid'");

		if(!empty($data['data']))
		{
			foreach($data['data'] as $val)
			{
				if($val['total'] > 0)
				{
					$result = $this->setAmount($val['total'])
								->setProcessor("Admin")
								->setClientId($client_id)
								->deductPayment($val['id']);
					if($result)
					{
						App::Model('Job')
						   ->setId($val['id'])
						   ->setPaymentstatus("Paid")
						   ->Save();
					}
				}
			}
		}
	}

	public function readDeposit($client_id=null)
	{
		$Payments = App::Model('Payment')->paging("client_id={$client_id} ORDER BY ID DESC",10);
		if(!empty($Payments['data']))
		{
			App::Module('DataGrid')->clear()->setHeader(Array("#","Processor","Amount","Date"))
								   ->setFooter($Payments['paging_str']);
			foreach($Payments['data'] as $Payment)
			{
				App::Module('DataGrid')->addRow($Payment['id'],$Payment['processor'],'$' . $Payment['total'],App::Helper('Date')->dateFormated($Payment['order_date']));
			}
			App::Module('DataGrid')->render();
		}
		else
		{
			echo "<h2>No data found</h2>";
		}
	}

	public function readPayment($client_id=null)
	{
		$Payments = App::Model('Expense')->paging("client_id={$client_id} ORDER BY ID DESC",10);

		if(!empty($Payments['data']))
		{
			App::Module('DataGrid')->clear()->setHeader(Array("#","Job","Amount","Date"))
								   ->setFooter($Payments['paging_str']);
			foreach($Payments['data'] as $Payment)
			{
				$job = App::Model('Job')->findById($Payment['job_id']);
				$job['title'] = isset($job['title']) ? App::Helper('Html')->linkTag(App::Config()->baseUrl("/pcjobs/manage/view/{$job['id']}"),$job['title']) : "";
				App::Module('DataGrid')->addRow($Payment['id'],$job['title'],'$' . $Payment['total'],App::Helper('Date')->dateFormated($Payment['pay_date']));
			}
			App::Module('DataGrid')->render();
		}
		else
		{
			echo "<h2>No data found</h2>";
		}
	}

	public function getDeposit($client_id=null)
	{
		$data = App::Model('Account')->findByClient_id($client_id);
		return isset($data['balance']) ? $data['balance'] : "0";
	}

	public function calculateEndDate($Job=null)
	{
		if(!is_array($Job))$Job = App::Model('Job')->findByid($Job);

		if($Job['start_date'] =="") return "";

		$start_date = $Job['start_date'];

		$DT = App::Model('Category')->findById($Job['delivery_time']);


		if($DT['title']=="")
		{
			$DT['title'] = '24 hours';
		}

		$period = ((int)$DT['title']) * 60 * 60;
		$end_date = $Job['end_date'];

		$legend = $this->getLegend($start_date,$end_date,$period);
		$end_date = (!$end_date)?"":App::Helper('Date')->dateFormated($end_date);

		return array("enddate"=>$end_date,"legend"=>$legend);

	}

	public function getLegend($s,$e,$p)
	{
		$ext = null;
		if(!$e)
		{
			$e = time();
			$sp = $e - $s;

			//if($p)
			$p = round(($sp/$p)*100);

			$color = "";
			if($p >= 50 && $p <=75) $color = self::COLOR_TIME12;
			elseif($p > 75 && $p <=100) $color = self::COLOR_TIME14;
			elseif($p >100){ $color = self::COLOR_NOTCOMPLETE;/*$ext = "<a  title=\"{$p}%(" . round($sp/3600) . "H) time spent on this Job\" onclick=\"alert('{$p}%(" . round($sp/3600) . "H) time spent on this Job');\">Check Here</a>";*/}
		}
		else
		{
			$sp = $e - $s;

			$p = round(($sp/$p)*100);
			$color = "";
			if($p <=100) $color = self::COLOR_TIMEON;
			else {$color = self::COLOR_TIMEXTRA;/*$p = $ext = "<a  title=\"{$p}%(" . round($sp/3600) . "H) time spent on this Job\" onclick=\"alert('{$p}%(" . round($sp/3600) . "H) time spent on this Job');\">Check Here</a>";*/}
		}

		return array($color,(isset($ext)?$ext:"{$p}%"));
	}

	public function memberListBox($name="data[Member][name]",$selected="")
	{
		$arr = App::Model('Member')->findAll("1 ORDER BY name asc");
		$html = "<select name=\"{$name}\"><option value=\"\"></option>";
		foreach($arr['data'] as $val)
		{
			if($val['name']!="")
			{
				if($selected == $val['id'])$html .= "<option value=\"{$val['id']}\" selected=\"selected\">{$val['name']}</option>";
				else $html .= "<option value=\"{$val['id']}\">{$val['name']}</option>";
			}

		}
		$html .= '</select>';
		return $html;
	}
	public $paymentstatus = Array('Paid'=>'Paid','NotPaid'=>'NotPaid');
	public function paymentStatus($status)
	{
		return isset($this->paymentstatus[$status])  ? $this->paymentstatus[$status] : "NotPaid";
	}
}